package controllers

import (
	"fmt"
	models "gotest/models"
	pager "gotest/pager"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type RecordController struct {
	beego.Controller
}

func (c *RecordController) List() {
	if c.GetSession("UserName") != nil {
		c.Data["IsAdmin"] = true
	}
	c.Layout = "basic-layout.tpl"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Header"] = "header.tpl"
	c.LayoutSections["Footer"] = "footer.tpl"
	userId := c.Ctx.Input.Param(":id")
	var page int
	var num int
	var pagesize int = 10 //每页多少条数据
	var pageBegin int
	p := c.Ctx.Input.Param(":page") //获取页数
	page, _ = strconv.Atoi(p)
	if page < 1 {
		page = 1
	}
	pageBegin = (page - 1) * pagesize
	var records []models.RestRecord
	o := orm.NewOrm()
	o.Using("default") // 默认使用 default，你可以指定为其他数据库
	sSql := "select r.id as id,u.name as user_name,case record_type when 0 then '加班' when 1 then '调休' end as rest_type,rest_hours,record_time,rest_date from rest_record as r join user as u on r.user_id=u.id where u.id=" + userId + " limit " + strconv.Itoa(pageBegin) + "," + strconv.Itoa(pagesize)
	//	_, err := o.QueryTable("restrecord").All(&records)
	_, err := o.Raw(sSql).QueryRows(&records)
	if err != nil {
		fmt.Println("读取数据库出错", err)
	}
	sSql = "select count(id) from rest_record where user_id=" + userId
	o.Raw(sSql).QueryRow(&num)
	var pages pager.Page = pager.NewPage(page, pagesize, num, "/Record/List/"+userId)
	c.Data["page"] = pages.Show()
	c.Data["Records"] = records
	c.Data["UserId"] = userId
	c.TplName = "record/list.tpl"
}

func (main *RecordController) InserRecord() {
	record := models.RestRecord{}
	if err := main.ParseForm(&record); err != nil {
		beego.Error("无法解析. 原因: ", err)
	} else {
		flash := beego.NewFlash()
		o := orm.NewOrm()
		o.Using("default")
		record.RecordTime = time.Now()
		_, err := o.Insert(&record)
		if err != nil {
			o.Rollback()
			beego.Error(err)
		} else {
			o.Commit()
			hours := strconv.Itoa(record.RestHours)
			if record.RecordType == 0 {
				sSql = "update User set Hours=Hours+" + hours + " where Id=" + strconv.Itoa(record.UserId)
			} else {
				sSql = "update User set Hours=Hours-" + hours + " where Id=" + strconv.Itoa(record.UserId)
			}
			_, err := o.Raw(sSql).Exec()
			if err != nil {
				fmt.Println(err)
			}
			msg := fmt.Sprintf("记录添加成功")
			beego.Debug(msg)
			flash.Notice(msg)
			flash.Store(&main.Controller)
		}
		url := "/Record/List/" + strconv.Itoa(record.UserId) + "/1"
		main.Ctx.Redirect(302, url)
	}
}

func (main *RecordController) Delete() {
	main.Layout = "basic-layout.tpl"
	main.LayoutSections = make(map[string]string)
	main.LayoutSections["Header"] = "header.tpl"
	main.LayoutSections["Footer"] = "footer.tpl"
	main.TplName = "record/list.tpl"
	recordId, _ := strconv.Atoi(main.Ctx.Input.Param(":id"))
	beego.Info("RecordId为:", recordId)
	o := orm.NewOrm()
	o.Using("default")
	if exist := o.QueryTable("rest_record").Filter("Id", recordId).Exist(); exist {
		if num, err := o.Delete(&models.RestRecord{Id: recordId}); err == nil {
			beego.Info("删除成功", num)
		} else {
			beego.Error("删除失败: ", err)
		}
	} else {
		beego.Info("用户不存在.")
	}
	url := "/Record/List/" + strconv.Itoa(recordId) + "/1"
	main.Ctx.Redirect(302, url)
}

func (main *RecordController) Add() {
	userId, _ := strconv.Atoi(main.Ctx.Input.Param(":id"))
	beego.Info(userId)
	main.Layout = "basic-layout.tpl"
	main.Data["UserId"] = userId
	main.LayoutSections = make(map[string]string)
	main.LayoutSections["Header"] = "header.tpl"
	main.LayoutSections["Footer"] = "footer.tpl"
	main.TplName = "record/add.tpl"
}

func (main *RecordController) Edit() {
	record := models.RestRecord{}
	recordId, _ := strconv.Atoi(main.Ctx.Input.Param(":id"))
	o := orm.NewOrm()
	o.Using("default")
	o.QueryTable("rest_record").Filter("Id", recordId).One(&record)
	main.Data["Record"] = record
	main.Layout = "basic-layout.tpl"
	main.LayoutSections = make(map[string]string)
	main.LayoutSections["Header"] = "header.tpl"
	main.LayoutSections["Footer"] = "footer.tpl"
	main.TplName = "record/edit.tpl"
}

func (main *RecordController) UpdateRecord() {
	record := models.RestRecord{}
	if err := main.ParseForm(&record); err != nil {
		beego.Error("无法解析. 原因: ", err)
	} else {
		flash := beego.NewFlash()
		o := orm.NewOrm()
		o.Using("default")
		err = o.Begin()
		_, err := o.Update(&record)
		if err != nil {
			o.Rollback()
			beego.Error(err)
		} else {
			o.Commit()
			msg := fmt.Sprintf("用户修改成功")
			beego.Debug(msg)
			flash.Notice(msg)
			flash.Store(&main.Controller)
		}
		main.Ctx.Redirect(302, "/")
	}
}
